const express = require("express");
const userList = require("../data/userData.json");
const tokenList = require("../utils/token");
const { sign } = require("../utils/jwt");
// 用户
const user = express.Router();

// 用户信息
user.get("/info", function (req, res) {
  const id = req._id;
  const checkUser = userList.find((item) => item.id === id);
  if (!checkUser) {
    return res.send({
      code: 201,
      data: null,
      message: "获取用户信息失败！",
      ok: true,
    });
  } else {
    return res.send({
      code: 200,
      data: { ...checkUser },
      message: "成功",
      ok: true,
    });
  }
});
// 登录
user.post("/login", function (req, res) {
  const { username, password } = req.body;
  const checkUser = userList.find(
    (item) => item.username === username && item.password === password
  );
  if (!checkUser) {
    return res.send({
      code: 201,
      data: null,
      message: "账号密码不对！",
      ok: true,
    });
  } else {
    const token = sign({ id: checkUser.id });
    res.header("authorization", "Bearer " + token);
    return res.send({
      code: 200,
      data: "Bearer " + token,
      message: "成功",
      ok: true,
    });
  }
});
// 登出
user.post("/logout", function (req, res) {
  const token = req.headers.authorization.replace("Bearer ", "");
  tokenList.push(token);
  return res.send({
    code: 200,
    message: "成功",
    data: null,
    ok: true,
  });
});
// 菜单
user.get("/menu", function (req, res) {
  return res.send({
    code: 200,
    message: "成功",
    data: null,
    ok: true,
  });
});

module.exports = user;
